package net.sf.ghost4j.extensions.statics;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import net.sf.ghost4j.extensions.GhostscriptExtended;

public class GhostScriptExecutor {
	/*
	 * gs -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=firstANDsecond.pdf -dBATCH
	 * first.pdf second.pdf
	 */
	public static File mergePdf(File[] files, File result) {
		GhostscriptExtended gs = new GhostscriptExtended();
		gs.addOptions("-dNOPAUSE").addOption("-sDEVICE=pdfwrite").addOption(
				"-sOUTPUTFILE=" + result.getAbsolutePath()).addOption(
				" -dBATCH");
		for (File file : files) {
			gs.addOptions(file.getAbsolutePath());
		}
		gs.execute();
		return result;
	}

	/*
	 * << /BeginPage{0.90 0.90 scale} /Margins [350 500] >> setpagedevice
	 */
	public static File resizePdf(File result, Float width, Float height,
			Float scale) {
		File temp = new File(System.getProperty("java.io.tmpdir")
				+ File.separator, "scale.ps");
		Writer output = null;
		try {
			output = new BufferedWriter(new FileWriter(temp));
			output.write("<< /BeginPage{" + width + " " + height
					+ " scale} /Margins [" + width + " " + height
					+ "] >> setpagedevice");
			output.close();
		} catch (IOException e) {

			e.printStackTrace();
		}
		GhostscriptExtended gs = new GhostscriptExtended();
		gs.addOptions("-dNOPAUSE").addOption("-sDEVICE=pdfwrite").addOption(
				temp.getAbsolutePath()).addOption(
				"-sOUTPUTFILE=" + result.getAbsolutePath()).addOption(
				" -dBATCH");
		temp.deleteOnExit();
		return result;
	}

	/*
	 * -dFirstPage=from -dLastPage=to
	 */
	public static File cropPages(File pdf, int from, int to, File result) {
		if (from < 1)
			from = 1;
		if (to < from)
			to = from;
		GhostscriptExtended gs = new GhostscriptExtended();
		gs.addOptions("-dNOPAUSE")
		.addOption("-sDEVICE=pdfwrite")
		.addOption(
				" -dBATCH")
				.addOption("-dFirstPage=" + from)
				.addOption(
				"-dLastPage=" + to)
				.addOption(
				"-sOUTPUTFILE=" + result.getAbsolutePath());
		gs.execute();
		return result;

	}

	/*
	 * gs -dPDFX=true -dNOOUTERSAVE -dNOPAUSE -dBATCH -dSAFER
	 * -dPDFSETTINGS=/prepress -sDEVICE=pdfwrite -dEmbedAllFonts=true
	 * -sOutputFile=nomeFilePDFUnico.pdf
	 */
	public static File embeddAllFonts(File pdf) {
		GhostscriptExtended gs = new GhostscriptExtended();
		gs.addOptions("-dPDFX=true").addOption("-dNOOUTERSAVE").addOption(
				"-dNOPAUSE").addOption("-dBATCH").addOption("-dSAFER")
				.addOption("-dPDFSETTINGS=/prepress").addOption(
						"-sDEVICE=pdfwrite").addOption("-dEmbedAllFonts=true")
				.addOption("-sOutputFile=" + pdf.getAbsolutePath());
		gs.execute();
		return pdf;

	}
}
